import {
  defineComponent,
  ref,
  reactive,
  computed,
  onBeforeMount,
  onMounted,
  provide,
  toRefs,
  getCurrentInstance,
} from 'vue';
import {
  INPUT_WORD_LIMIT,
  ATTACHMENT_MAX_SIZE,
  ATTACHMENT_MAX_SIZE_KEY,
  RECENTLY_MENTIONED_USERS_KEY,
} from './utils';
// mock data
import { useQuasar } from '@teld/q-components';

import TmComment from './mobile/index.vue';
import TpComment from './pc/index.vue';
import { checkDirty } from './hooks/useCheckDirty.js';
import {
  getUserInfoFromSession,
  getUserProfiles,
  saveUserStringProfile,
  getSysLoginUser,
} from './hooks/api.js';
import { RECENTLY_MENTIONED_USERS_LIMIT } from './utils/constants.js';
//
import useMappingProps from 't/common/hooks/useMappingProps';

// 用于控制组件是否使用mock数据，文档项目需要使用mock数据进行展示
export const isUseMock = ref(false);

export default defineComponent({
  name: 'TComment',
  props: {
    visible: {
      type: Boolean,
      default: true,
    },
    isMobile: {
      type: Boolean || null || undefined,
      default: null,
    },
    /** 紧凑模式 */
    dense: {
      type: Boolean,
      default: false,
    },
    sendButtonText: {
      type: String,
      default: '',
    },
    inputMaxLength: {
      type: Number,
      default: INPUT_WORD_LIMIT,
    },
    /**
     * @deprecated
     */
    fasUrl: {
      type: String,
      default: '',
    },
    /**
     * 通知链接为非前页面地址，需要传入，
     * 通知链接为当前页面地址，不需传入，
     * 有传入用传入，无传入则默认为当前页面地址
     */
    notificationLink: {
      type: String,
      default: '',
    },
    /**
     * @deprecated
     */
    isInWebFramework: {
      type: Boolean,
      default: false,
    },
    disableNotifications: {
      type: Boolean,
      default: false,
    },
    // -- 开发&文档用参数 --
    isUseMock: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['comment'],
  setup(props, ctx) {
    const { attrs, expose, emit } = ctx;
    const { isInWebFramework, disableNotifications, notificationLink } =
      toRefs(props);

    isUseMock.value = props.isUseMock;
    const attachmentMaxSize = ref(ATTACHMENT_MAX_SIZE);
    const recentlyMentionedUsers = ref([]);
    const $q = useQuasar();
    const isLoading = ref(false);
    const loginUserInfo = reactive({
      // avatar: 'Avatar || headImg',
      // userId: 'UserId',
      // userName: 'UserName',
    });
    const [mappingProps, mappingExpose] = useMappingProps(props, {});

    provide(
      'qLangComment',
      computed(() => $q.lang?.comment || {}),
    );
    provide('dense', props.dense);
    // provide('emptyText', props.emptyText);
    provide('loginUserInfo', loginUserInfo);
    provide('sendButtonText', props.sendButtonText);
    provide('inputMaxLength', props.inputMaxLength);
    provide('notificationLink', () => {
      // 如果关闭了通知
      if (disableNotifications.value) return '';
      // ----开启通知的情况--
      const trimmedUrl =
        notificationLink.value && notificationLink.value.trim();
      return trimmedUrl || location.href;
    });
    // provide('pageUrl', () => {
    //   // 如果关闭了通知
    //   if (disableNotifications.value) return '';
    //   // ----开启通知的情况--
    //   // 1. 页面在web框架中
    //   if (isInWebFramework.value) {
    //     // web 框架中时需要子应用的url，否则通知链接无法进入该子应用的页面
    //     return fasUrl.value && fasUrl.value.trim()
    //       ? fasUrl.value.trim()
    //       : '';
    //   }
    //   // 2. 页面独立打开，不需要这个用于web框架的fpath参数
    //   return '';
    // });
    provide('getAttachmentMaxSize', () => {
      // TODO
      return attachmentMaxSize;
    });
    provide('recentlyMentionedUsers', recentlyMentionedUsers);
    provide('updateRecentlyMentionedUsers', item => {
      const items = Array.isArray(item) ? item : [item];
      // 去重，顶部push压栈，更新当前变量，更新到数据库
      const newList = [
        ...items,
        ...recentlyMentionedUsers.value.filter(n => !items.some(o => o.UserID === n.UserID)),
      ].slice(0, RECENTLY_MENTIONED_USERS_LIMIT);
      recentlyMentionedUsers.value = newList;
      saveUserStringProfile(recentlyMentionedUsers.value);
    });
    provide('emitEvent', (code = 'comment', data = null) => {
      emit(code, data);
    });

    console.log('comment', props, attrs, ctx.attrs);

    const vmInstance = getCurrentInstance();
    mappingExpose.checkDirty = () => checkDirty(vmInstance.proxy.$el);
    expose(mappingExpose);

    async function getLoginUserInfo() {
      try {
        // const userInfo = await TFF.common.ajax.getSession();
        // const userInfo = await getUserInfoFromSession();

        const { Avatar, UserID, RealName } = await getSysLoginUser();
        Object.assign(loginUserInfo, {
          avatar: Avatar,
          userId: UserID,
          userName: RealName,
        });
      } catch (error) {
        console.log(error);
      }
    }
    async function getUserProfileInfo() {
      try {
        const data = await getUserProfiles();

        if (!data || data.state !== '1') {
          return;
        }
        const _data_ = data.data;
        attachmentMaxSize.value =
          _data_[ATTACHMENT_MAX_SIZE_KEY] || ATTACHMENT_MAX_SIZE;
        recentlyMentionedUsers.value = JSON.parse(
          _data_[RECENTLY_MENTIONED_USERS_KEY] || '[]',
        );
        console.log(
          `UserProfile${ATTACHMENT_MAX_SIZE_KEY}=${attachmentMaxSize.value}`,
        );
        // TODO mock
        // if (!this.recentlyMentionedUsers.length) {
        //   this.recentlyMentionedUsers = mockUserList;
        // }
      } catch (error) {
        console.log(error);
      }
    }

    async function init() {
      getLoginUserInfo();
      getUserProfileInfo();
    }

    onBeforeMount(() => {
      init();
    });

    onMounted(() => {});

    return () =>
      mappingProps.visible ? (
        <>
          {/* {mappingProps.isMobile ? ( */}
          {$q.platform.is.mobile ? (
            <TmComment {...attrs} visible={mappingProps.visible}></TmComment>
          ) : (
            <TpComment {...attrs} visible={mappingProps.visible}></TpComment>
          )}
        </>
      ) : null;
  },
});
